package base.IO流;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class 压缩流 {
    public static void main(String[] args) throws IOException {
        File src = new File("C:\\Users\\TUO\\Desktop\\kali");
        File destParent = src.getParentFile();//父级路径（上一个文件夹的路径）
        System.out.println(destParent);
        File dest = new File(destParent,src.getName() + ".zip");
        //Charset ch = Charset.forName("GBK");
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest));

        tozip(src,src.getName(),zos);
        zos.close();
    }

    private static void tozip(File src,String path,ZipOutputStream zos) throws IOException {
        File[] files = src.listFiles();
        for (File file : files){
            if (file.isFile()){
                //需要压缩的是文件
                ZipEntry entry = new ZipEntry(path + "\\" + file.getName());
                zos.putNextEntry(entry);//把zipEntry对象放入压缩包流中（zipEntry生效）
                //关联zipEntry对象只有空文件，需要写入数据
                FileInputStream fis = new FileInputStream(file);
                int len;
                byte[] bytes = new byte[1024 * 8];
                while ((len = fis.read(bytes)) != -1){
                    zos.write(bytes,0,len);
                }
                fis.close();
                zos.closeEntry();
            }else {
                //src是文件夹
                /*zipEntry会补全路径的文件夹*/
                tozip(file,path + "\\" + file.getName(),zos);
            }
        }
    }
}
